package hydrap2p.hubcli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.thrift.TException;

import hydrap2p.helper.ServiceConnector;
import hydrap2p.hub.HubManager;
import hydrap2p.hub.HubStatus;
import hydrap2p.hub.NameNotFound;
import hydrap2p.hub.ProtocolNotConnected;

public class Main {

	public static void main(String[] args) throws TException
	{
		boolean running=true;
		BufferedReader inputreader=new BufferedReader(new InputStreamReader(System.in));
		HubManager.Iface connection=ServiceConnector.getService(HubManager.Client.class, "HubManager");
		while (running)
		{
			List<HubStatus> statuses=connection.getStatuses();
			for (int i=0; i<statuses.size(); i++)
			{
				HubStatus status=statuses.get(i);
				System.out.println(i+". "+status.getHubtype()+":"+status.getName()+" CON "+(status.connected?"Y":"N") + " AUTO "+(status.autoconnect?"Y":"N"));
			}
			System.out.println("X. Quit");
			

			String input="";
			try {
				input=inputreader.readLine();
			} catch (IOException e) {
				return;
			}
			
			System.out.println();
			
			if (input.toLowerCase().equals("x"))
			{
				return;
			}
			
			// parse numeric input
			int selection=0;
			try {
				selection=Integer.parseInt(input);
			}
			catch (Exception e){
				System.out.println("Could not parse your input");
				continue;
			}
			
			if (selection<0 || selection>=statuses.size())
			{
				System.out.println("Could not parse your input");
				continue;
			}
			
			HubStatus current=statuses.get(selection);
			System.out.println("A. "+(current.autoconnect?"disable":"enable")+" autoconnect");
			System.out.println("C. "+(current.connected?"disconnect":"connect"));
			

			input="";
			try {
				input=inputreader.readLine();
			} catch (IOException e) {
				return;
			}
			
			if (input.equalsIgnoreCase("a"))
			{
				try {
					connection.changeConnection(current.hubtype, current.name, current.params, !current.autoconnect);
				} catch (NameNotFound e) {
					System.out.println("Connection profile removed");
				}
			}
			if (input.equalsIgnoreCase("c"))
			{
				if (current.connected)
					connection.disconnect(current.hubtype, current.name);
				else
				{
					try {
						connection.connect(current.hubtype, current.name);
					} catch (NameNotFound e) {
						System.out.println("Connection profile removed");
					} catch (ProtocolNotConnected e) {
						System.out.println("Protocol not connected");
					}
				}
			}
			System.out.println();
		}
	}
}
